<?php
class UsersController extends AppController
{
	var $name='Users';
	var $uses=array('User','Cliente','Direccione','Menu','Producto','Dato');
	var $components = array('RequestHandler','SwiftMailer');
	
	
	function beforeFilter()
		{
			if($this->Session->read('admin')==2)
			{
				$this->layout = 'medio';
			}
			if($this->Session->read('admin')==1)
			{
				$this->layout = 'default';
			}
			if($this->Session->read('admin')==0)
			{
				$this->layout = 'bajo';
			}
		}
	
	
	function login()    
	{ 
		$horaLimites=$this->Dato->field('horafinal',array('id'=>1));
		$this->User->recursive=1;
		Configure::write('debug', 0);
		
		/*Redirrecionamiento automatico para sesiones creadas*/
		if($this->Session->read('idUser') && !$this->Session->read('admin')){
			//$this->redirect(array('controller'=>'pedidos','action'=>'index'));
			$this->redirect('/users/trans');
		}
		elseif ($this->Session->read('idUser') && $this->Session->read('admin')){
			//$this->redirect(array('controller'=>'admins','action'=>'index'));
			$this->redirect('/users/transAdmin');
		}
		else
		{
		
		/*Control de Hora para el Login*/
		//if(date('His') < str_replace(':','',$horaLimites))
		//{
			if(!empty($this->data))
			{
						if($this->data['User']['username']!="C.I")
						{
							if($this->User->findByUsername($this->data['User']['username']))
							{
								$id=$this->User->field('id',array('username'=>$this->data['User']['username']));
								$pass=$this->User->field('password',array('username'=>$this->data['User']['username']));
								if ($pass==$this->data['User']['password'])
								{	
									if($this->User->field('admin',array('username'=>$this->data['User']['username']))==0){
											$this->Session->write('nombre',$this->User->field('nombre',array('username'=>$this->data['User']['username'])));
											$this->Session->write('idUser',$id);
											//$this->redirect(array('controller'=>'pedidos','action'=>'index'));
											$this->redirect('/users/trans');
										}
									if($this->User->field('admin',array('username'=>$this->data['User']['username']))==1 && $this->User->field('activo',array('username'=>$this->data['User']['username']))!=0){
											$this->Session->write('nombre',$this->User->field('nombre',array('username'=>$this->data['User']['username'])));
											$this->Session->write('admin',1);
											$this->Session->write('idUser',$id);
											//$this->redirect(array('controller'=>'admins','action'=>'index'));
											$this->redirect('/users/transAdmin');
										}else{
                                                                                    $this->Session->write('long','Usuario Inhabilitado');
                                                                                }
									if($this->User->field('admin',array('username'=>$this->data['User']['username']))==2 && $this->User->field('activo',array('username'=>$this->data['User']['username']))!=0){
											$this->Session->write('nombre',$this->User->field('nombre',array('username'=>$this->data['User']['username'])));
											$this->Session->write('admin',2);
											$this->Session->write('idUser',$id);
											//$this->redirect(array('controller'=>'admins','action'=>'index'));
											$this->redirect('/users/transAdmin');
										}else{
                                                                                    $this->Session->write('long','Usuario Inhabilitado');
                                                                                }
								}
								else{
								$this->Session->write('long','C&eacute;dula o Correo Inv&aacute;lidos, Verifique');
								}
							}
							else{
								$this->Session->write('long','C&eacute;dula o Correo Inv&aacute;lidos, Verifique');
							}
						}
						else{
							$this->Session->write('long','Debe Ingresar sus Datos');
						}
			}	
		/*	
		}
		else
		{
			$this->transHora($horaLimites);
			$this->render('transHora'); 
			//transHora($horaLimites);
		}
		*/
		
		}
	}
	
	function trans(){
	}
	function transAdmin(){
	}
	function transHora($hora){
		$this->set('horaLimite',$hora);
	}
	
	function logout() 
    { 
        $this->Session->destroy('user'); 
        $this->redirect( array(
					'controller'    =>      'menus' ,
					'action'        =>      'index' ,
			));
    } 
	
	function recuperar()
	{
		$this->User->recursive=1;
		$this->Session->delete('recup');
		if(!empty($this->data))
		{
			if($this->data['User']['username']!="C�dula" && $this->data['Cliente']['mail']!="E-mail")
			{
				if($this->User->findByUsername($this->data['User']['username']))
				{
					$this->User->find('first', array('conditions' => array('User.username' => $this->data['User']['username']),'fields'=>array('username','password')));
					$id=$this->User->field('id',array('username'=>$this->data['User']['username']));
					$nombre=$this->User->field('nombre',array('id'=>$id));
					$pass=$this->User->field('password',array('username'=>$this->data['User']['username']));
					$this->User->Cliente->findByUserId($id);
					$correo=$this->User->Cliente->field('mail',array('user_id'=>$id));
					$telefono=$this->User->Cliente->field('telefono',array('user_id'=>$id));
					$celular=$this->User->Cliente->field('celular',array('user_id'=>$id));
					$direccionId=$this->User->Cliente->field('direccione_id',array('user_id'=>$id));
					$direccion=$this->Direccione->field('torre',array('id'=>$direccionId));
					$empresa=$this->User->Cliente->field('empresa',array('user_id'=>$id));
					$piso=$this->User->Cliente->field('piso',array('user_id'=>$id));
					$oficina=$this->User->Cliente->field('oficina',array('user_id'=>$id));
					$sexo=$this->User->Cliente->field('sexo',array('user_id'=>$id));
					if ($correo==$this->data['Cliente']['mail']){
						$this->enviar($this->data['User']['username'],$nombre,$pass,$correo,$telefono,$celular,$direccion,$empresa,$piso,$oficina,$sexo);
					}
					else{
						$this->Session->write('recup','C�dula o Correo Inv�lidos, Verifique');
					}
					
				}
				else{
					$this->Session->write('recup','C�dula o Correo Inv�lidos, Verifique');
				}
			}
			else{
				$this->Session->write('recup','Debe ingresar sus datos');
			}
		}
		else{
			$this->Session->write('recup','Debe ingresar sus datos');
		}
	}
	function enviado()
	{}
	function enviar($cedula,$nombre,$clave,$correo,$telefono,$celular,$direccion,$empresa,$piso,$oficina,$sexo)
	{
		
            /*NUEVO COMPONENTE*/
            $this->SwiftMailer->smtpType = $this->tipoSmtp;
            $this->SwiftMailer->smtpHost = $this->hostSmtp;
            $this->SwiftMailer->smtpPort = $this->puertoSmtp;
            $this->SwiftMailer->smtpUsername = $this->usernameSmtp;
            $this->SwiftMailer->smtpPassword = $this->passwordSmtp;
            $this->SwiftMailer->sendAs = $this->enviarComo;
            $this->SwiftMailer->from = $this->remitente;
            $this->SwiftMailer->fromName = 'Recuperación Cuenta ProntoDeli';
            $this->SwiftMailer->to = $correo;

            $this->set('nombre',$nombre);
            $this->set('correo',$correo);
            $this->set('cedula',$cedula);
            $this->set('clave',$clave);
            $this->set('telefono',$telefono);
            $this->set('celular',$celular);
            $this->set('direccion',$direccion);
            $this->set('empresa',$empresa);
            $this->set('piso',$piso);
            $this->set('oficina',$oficina);
            $this->set('sexo',$sexo);
		
		//$this->SwiftMailer->send();
        try { 
            if(!$this->SwiftMailer->send('recuperar', 'Reenvio de Datos de Usuario')) { 
                $this->log("Error sending email");
				$this->Session->write('envi','Error, correo no enviado, Intente de nuevo');
				$this->redirect(array(
							'controller'=>'users',
							'action'=>'enviado'));
            } 
        } 
        catch(Exception $e) { 
              $this->log("Failed to send email: ".$e->getMessage()); 
			  
        } 
        //$this->redirect($this->referer(), null, true); 
		
		$this->Session->write('envi','Datos enviados a su cuenta');
		$this->redirect(array(
							'controller'=>'users',
							'action'=>'enviado'));
							
	}
	
	//function enviarMenu($correo)
	function enviarMenu()
	{
	
		$this->SwiftMailer->smtpType = $this->tipoSmtp;
                $this->SwiftMailer->smtpHost = $this->hostSmtp;
                $this->SwiftMailer->smtpPort = $this->puertoSmtp;
                $this->SwiftMailer->smtpUsername = $this->usernameSmtp;
                $this->SwiftMailer->smtpPassword = $this->passwordSmtp;
                $this->SwiftMailer->sendAs = $this->enviarComo;
                $this->SwiftMailer->from = $this->remitente;
                $this->SwiftMailer->fromName = 'Menú Pronto Deli';
		//$this->SwiftMailer->to = $correo; 
		
		$fechaDate=date('Y-m-d');
		$productosPrincipal=$this->Producto->Menu->find('all',array('conditions'=>array('Menu.fecha'=>$fechaDate)));
		$correos=$this->User->Cliente->find('all',array('conditions'=>array('Cliente.recibirmail'=>1)));
		
		$this->set('productosPrincipal',$productosPrincipal);
                if($correos){
                    foreach($correos as $correo){
                        $this->SwiftMailer->to = $correo['Cliente']['mail'];
                        try { 
                            if(!$this->SwiftMailer->send('menus_diarios', 'Pronto Deli')) { 
                                $this->log("Error sending email");
                            } 
                            }catch(Exception $e) { 
                                $this->log("Error enviando Email: ".$e->getMessage()); 
                            }
                    }
                }


                //$this->set('productosPrincipal',$productosPrincipal);
                //$this->SwiftMailer->to = $correo['Cliente']['mail'];
                /*
                $this->SwiftMailer->to = 'juan.escalante22@gmail.com';
                try {
                if(!$this->SwiftMailer->send('menus_diarios', 'Pronto Deli')) {
                        $this->log("Error sending email");
                }
                }
                        catch(Exception $e) {
                        $this->log("Error enviando Email: ".$e->getMessage());
                }
                 */
                //$this->redirect($this->referer(), null, true);
		exit();
		
	}
	
	function adminIndex()
	{
		$this->User->recursive=1;
		if($this->Session->read('admin')){
			$this->set('administradores',$this->User->find('all',array('conditions'=>array('admin != '=>0))));
		}
		else{
			$this->Session->write('&Aacute;rea restringida');
			$this->Redirect('/menus/index');
		}
		
	}
}
?>